import { createRouter, createWebHistory, type RouteRecordRaw } from "vue-router";

// 读取modules文件内的模块路由
const modules = import.meta.glob(["./modules/*.ts"], { eager: true });
const routers: Array<RouteRecordRaw> = [];

Object.keys(modules).forEach((key) => {
  const module = (modules[key] as any).default;
  routers.push(module);
});

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routers,
});

const token = localStorage.getItem("token");
const routerWhiteList = ["/login"];

// 路由守卫
router.beforeEach((to, from) => {
  // 白名单不验证token
  if (routerWhiteList.includes(to.path)) {
    return true;
  }

  if (token) {
    return true;
  }
  {
    router.push({
      path: "/login",
      query: {
        redirect: to.fullPath,
      },
    });
    return false;
  }
});

export default router;
